package com.mytx.common.utils;



import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class AESUtil {
    //生成AES秘钥，然后Base64编码
    public final static String ENCODING = "UTF-8";

    public static String genKeyAES() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        return byte2Base64(key.getEncoded());
    }

    //将Base64编码后的AES秘钥转换成SecretKey对象
    public static SecretKey loadKeyAES(String base64Key) throws Exception {
        byte[] bytes = base642Byte(base64Key);

        SecretKeySpec key = new SecretKeySpec(bytes, "AES");
        return key;
    }


    //加密
    public static byte[] encryptAES(byte[] source, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(source);
    }

    //解密
    public static byte[] decryptAES(byte[] source, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(source);
    }


    public static String byte2Base64(byte[] bytes)  {

        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(bytes);

    }


    public static byte[] base642Byte(String src)  {
        Base64.Decoder decoder = Base64.getDecoder();
        decoder.decode(src);
        // 执行解码
        return decoder.decode(src);
    }

}
